import 'dart:io';
import 'dart:typed_data';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:dali_ng_pera/manager/dnp_plugin_manager.dart';
import 'package:dali_ng_pera/mob/dnp_mob.dart';
import 'package:dali_ng_pera/page/certification/controller/dnp_identity_photo_controller.dart';
import 'package:dali_ng_pera/page/certification/dialog/dnp_identity_correct_dialog.dart';
import 'package:dali_ng_pera/page/certification/enum/identity_enum.dart';
import 'package:dali_ng_pera/page/certification/utils/dnp_certification_jump_utils.dart';
import 'package:dali_ng_pera/page/widget/dnp_app_bar.dart';
import 'package:dali_ng_pera/plugin/dnp_plugin/lib/dnp_plugin.dart';
import 'package:dali_ng_pera/tool/dnp_time_tool.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'dialog/dnp_identity_please_confirm_dialog.dart';
import 'dnp_identity_information_page.dart';
import 'model/dnp_identity_model.dart';

class DnpIdentityPhotoPage extends StatefulWidget {
  final String title;
  final String already;

  const DnpIdentityPhotoPage({super.key, required this.already,required this.title});

  @override
  State<DnpIdentityPhotoPage> createState() => _DnpIdentityPhotoPageState();
}

class _DnpIdentityPhotoPageState extends State<DnpIdentityPhotoPage> {
  final controller = Get.put(DnpIdentityPhotoController());
  int allStartTime = 0;
  int faceStartTime = 0;
  int faceEndTime = 0;

  @override
  void initState() {
    super.initState();
    allStartTime = DnpTimeTool.timestamp;
    controller.onRequestData(widget.already);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFF53A9FF),
              Color(0xFFDFF1FF),
            ],
          ),
        ),
        child: Column(
          children: [
            DnpAppBar(title: widget.title),
            Expanded(
                child: SingleChildScrollView(
                    child: Column(
              children: [
                _buildDescription(),
                Obx(() => _buildIdentityItem(
                    controller.photoModel.value?.id_front_msg ??
                        "Front of ID photo",
                    controller.photoModel.value?.death?.belated ??
                        (controller.frontUploadModel.value.belated ?? ""),
                    "assets/images/ic_identity_photo_bg1.webp",
                    controller.photoModel.value?.death?.proportions == 1,
                    onTap: onTapPhoto)),
                Obx(() => _buildIdentityItem(
                    controller.photoModel.value?.face_msg ??
                        "Facial recognition",
                    controller.photoModel.value?.clergyman?.belated ??
                        (controller.faceUploadModel.value.belated ?? ""),
                    "assets/images/ic_identity_photo_bg2.webp",
                    controller.photoModel.value?.clergyman?.proportions == 1,
                    onTap: onTapFacial)),
              ],
            ))),
            _buildBottomButton(),
          ],
        ),
      ),
    );
  }

  Widget _buildDescription() {
    return Container(
      margin: EdgeInsets.all(14),
      padding: EdgeInsets.all(14),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(20)),
      ),
      child: Text(
        "Please upload your personal information (rest assured that your information and data are protected)",
        style: TextStyle(
          color: Color(0xFFABABAB),
          fontSize: 16,
          fontWeight: FontWeight.w400,
        ),
      ),
    );
  }

  Widget _buildIdentityItem(
      String title, String fileSrc, String localeScr, bool isComplete,
      {VoidCallback? onTap}) {
    return Padding(
      padding: const EdgeInsets.only(left: 14, right: 14, top: 2, bottom: 14),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFF252630)),
          ),
          const SizedBox(
            height: 17,
          ),
          Container(
              width: double.infinity,
              height: 201,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(20),
                    topRight: Radius.circular(20)),
              ),
              child: isComplete
                  ? CachedNetworkImage(
                      imageUrl: fileSrc,
                      width: 275,
                      height: 173,
                      fit: BoxFit.cover,
                      errorWidget: (a, b, c) {
                        return Image.asset(
                          localeScr,
                          width: 275,
                          height: 173,
                          fit: BoxFit.cover,
                        );
                      },
                      placeholder: (a, b) {
                        return Image.asset(
                          localeScr,
                          width: 275,
                          height: 173,
                          fit: BoxFit.cover,
                        );
                      },
                    )
                  : Image.asset(
                      localeScr,
                      width: 275,
                      height: 173,
                      fit: BoxFit.cover,
                    )),
          GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: onTap,
            child: Container(
              width: double.infinity,
              height: 45,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: isComplete
                    ? Color(0xFF5286AC).withValues(alpha: 0.41)
                    : Color(0xFF0193FE),
                borderRadius: BorderRadius.only(
                    bottomLeft: Radius.circular(20),
                    bottomRight: Radius.circular(20)),
              ),
              child: Image.asset(
                "assets/images/ic_identity_photo_icon.webp",
                width: 31,
                height: 31,
                color: isComplete ? Color(0xFF81ABCB) : Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildBottomButton() {
    return GestureDetector(
      onTap: () {
        if (controller.photoModel.value?.death?.proportions == 1 &&
            controller.photoModel.value?.clergyman?.proportions == 1) {
          Get.back();
          // controller.onRequestNext(widget.already, (value) {
          //   DnpCertificationJumpUtils.jump(value, widget.already);
          // });
        } else if (controller.photoModel.value?.death?.proportions != 1) {
          onTapPhoto();
        } else if (controller.photoModel.value?.clergyman?.proportions != 1) {
          onTapFacial();
        }
      },
      child: Container(
        width: double.infinity,
        height: 48,
        alignment: Alignment.center,
        margin: EdgeInsets.only(left: 24, right: 24, bottom: 34, top: 10),
        decoration: BoxDecoration(
          color: Color(0xFF1D4AC8),
          borderRadius: BorderRadius.all(Radius.circular(16)),
        ),
        child: Text(
          "Next",
          style: TextStyle(
            color: Colors.white,
            fontSize: 16,
            fontWeight: FontWeight.w600,
          ),
        ),
      ),
    );
  }

  void onTapPhoto() {
    if (controller.photoModel.value == null) {
      controller.onRequestData(widget.already, callback: () {
        handleToPhoto(controller.photoModel.value!);
      });
    } else {
      handleToPhoto(controller.photoModel.value!);
    }
  }

  void handleToPhoto(DnpIdentityModel model) async {
    if (model.death?.proportions == 1) {
      return;
    }
    controller.curCircumstances = await Get.to(DnpIdentityInformationPage(
          attend: model.attend ?? [],
          begun: model.begun ?? [],
        )) ??
        "";
    controller.onRequestData(widget.already);
  }

  void onTapFacial() {
    if (controller.photoModel.value?.death == null ||
        controller.photoModel.value?.death?.proportions != 1) {
      onTapPhoto();
      return;
    }
    if (controller.photoModel.value?.clergyman?.proportions == 1) {
      return;
    }
    showDialog(
        context: context,
        builder: (context) {
          return DnpIdentityCorrectDialog(
            identityType: IdentityType.FacialRecognition,
            onNext: () async {
              faceStartTime = DnpTimeTool.timestamp;
              Map<dynamic, dynamic>? result = await DnpPlugin().showFrontCamera;
              controller.onUploadImage(
                  result?["imageBytes"] ?? [],
                  result?["isCameraOpen"] ?? false,
                  10,
                  controller.curCircumstances, callback: () {
                faceEndTime = DnpTimeTool.timestamp;
                DnpMob.inexplicable("4", faceStartTime, faceEndTime);
                controller.onRequestData(widget.already);
              });
            },
          );
        });
  }
}
